package com.euro.video.phone.dao.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.euro.video.phone.dao.PubliciteDao;
import com.euro.video.phone.entities.Publicite;

@Repository
@Transactional(propagation = Propagation.REQUIRED)
public class PubliciteDaoImpl implements PubliciteDao {
	@PersistenceContext
	private EntityManager manager;

	public Publicite creerPublicite(Publicite publicite) throws Exception {
		manager.persist(publicite);
		return publicite;
	}

	public Publicite lirePublicite(String titre) throws Exception {
		return manager.find(Publicite.class, titre);
	}

	public Publicite modifierPublicite(Publicite publicite) throws Exception {
		return manager.merge(publicite);
	}

	public boolean supprimerPublicite(Publicite publicite) throws Exception {
		try {
			manager.remove(manager.contains(publicite) ? publicite : manager.merge(publicite));
			return true;
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	@SuppressWarnings("unchecked")
	public List<Publicite> listPublicitesParDates(Date debut, Date fin)
			throws Exception {
		Query query = manager.createNamedQuery("listPublicitesParDates");
		query.setParameter("debut", debut);
		query.setParameter("fin", fin);
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<Publicite> listPublicitesALaUne() throws Exception {
		Query query = manager.createNamedQuery("listPublicitesALaUne");
		return query.getResultList();
	}

	public byte[] retrouverImage(String titre) throws Exception {
		Query query = manager.createNamedQuery("imagePublicite");
		query.setParameter("titre", titre);
		return (byte[]) query.getSingleResult();
	}

}
